package com.dau.common.util;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @author tzj
 * @date 2024/12/19
 */
@Component
public class RabbitTemplateUntil {
    private static final Logger logger = LoggerFactory.getLogger(RabbitTemplateUntil.class);
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息到指定队列
     *
     * @param queueName 队列名称
     * @param message   要发送的消息
     */
    public void sendMessage(String queueName, Object message) {
        try {
            rabbitTemplate.convertAndSend(queueName, message);
            logger.info("Message sent successfully: " + message);
        } catch (Exception e) {
            logger.error("Failed to send message: " + e.getMessage());
        }
    }

    /**
     * 发送到指定交换机和路由键
     *
     * @param exchange   交换机名称
     * @param routingKey 路由键
     * @param message    要发送的消息
     */
    public void sendMessageToExchange(String exchange, String routingKey, Object message) {
        try {
            rabbitTemplate.convertAndSend(exchange, routingKey, message);
            logger.info("Message sent successfully to exchange '" + exchange + "' with routing key '" + routingKey + "': " + message);
        } catch (Exception e) {
            logger.error("Failed to send message: " + e.getMessage());
        }
    }

    /**
     * 发送延迟消息到指定交换机和路由键
     *
     * @param exchange    交换机名称
     * @param routingKey  路由键
     * @param messageData 要发送的消息
     * @param delay       延迟时间（毫秒）
     */
    public void sendDelayedMessage(String exchange, String routingKey, Object messageData, String delay) {
        try {
            rabbitTemplate.convertAndSend(exchange, routingKey, messageData, message -> {
                // 添加延迟消息属性
                message.getMessageProperties().setExpiration(delay);
                return message;
            });
            logger.info("Delayed message sent successfully to exchange '" + exchange + "' with routing key '" + routingKey + "': " + messageData);
        } catch (AmqpException e) {
            logger.error("Failed to send delayed message: " + e.getMessage());
        }
    }
}
